package com.iscc.maoke.service.impl;

import com.iscc.maoke.dao.ImgDAO;
import com.iscc.maoke.dao.ProductDAO;
import com.iscc.maoke.dao.impl.ImgDAOImpl;
import com.iscc.maoke.dao.impl.ProductDAOImpl;
import com.iscc.maoke.domain.Img;
import com.iscc.maoke.domain.Product;
import com.iscc.maoke.service.ProductService;
import com.iscc.maoke.util.DataSourceUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class ProductServiceImpl implements ProductService {


    private ProductDAO productDAO = new ProductDAOImpl();
    private ImgDAO imgDAO = new ImgDAOImpl();

    @Override
    public int addProduct(Product product, List<Img> imgs) {
        Connection conn = null;
        int result = -1;
        try {
            conn = DataSourceUtil.getConnection();
            conn.setAutoCommit(false);
            int pno = productDAO.getNewId(conn);
            product.setPno(pno);
            int pResult = productDAO.add(conn, product);

            for (Img img : imgs) {
                img.setPno(pno);
            }

            int iResult = imgDAO.add(conn, imgs);

            if (pResult != -1 && iResult != -1) {
                conn.commit();
                result = 1;
            } else {
                conn.rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        return result;
    }
}
